package com.muh.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class FristConsumer {
    private static final String HOST_NAME = "39.104.74.101";
    private static final int PORT = 5672;
    private static final String QUEUE_NAME = "test2";//队列名称
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "admin";
    private static final String VIRTUAL_HOST = "/mirror";//虚拟机

    public static void main(String[] args) throws Exception {
        //建立连接Factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_NAME);
        factory.setPort(PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setVirtualHost(VIRTUAL_HOST);

        //建立连接
        Connection connection = factory.newConnection();
        //创建一个通道用来传输数据
        Channel channel = connection.createChannel();
//        Channel channel2 = connection.createChannel(1);
          //重复创建同一个编号的通道后面的为空 connection.createChannel(1);
//        System.out.println(channel2);

        /**
         * 申明一个对列，队列名，durable是否持久化，exclusive是否独占，autodelete是否自动删除消息
         * 这几个参数跟创建对列的页面是一致的
         * 如果broker上没有对列，那么就会自动创捷对列
         * 但是如果broker上已经有了这个对列，那么对列的属性必须匹配，否则会报错
         */
        Map<String, Object> params = new HashMap<String, Object>();
        channel.queueDeclare(QUEUE_NAME, true, false, false, params);

        channel.basicQos(100);//每个worker同时处理100个消息
        //回调函数，处理接收的消息
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("---------------------------");
                System.out.println("routingKey: " + envelope.getRoutingKey());
                System.out.println("contentType: " + properties.getContentType());
                long deliveryTag = envelope.getDeliveryTag();
                System.out.println("deliveryTag: " + deliveryTag);
                System.out.println("content: " + new String(body, "UTF-8"));
                channel.basicAck(deliveryTag, true);
                System.out.println("---------------------------");
            }
        };
        //从QUEUE_NAME对列发送或接收消息
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }
}
